package com.chf.job.controller;

import com.chf.job.common.Const;
import com.chf.job.common.ServerResponse;
import com.chf.job.pojo.User;
import com.chf.job.service.MailService;
import com.chf.job.service.UserService;
import com.chf.job.utils.CookieUtil;
import com.chf.job.utils.MD5Util;
import com.chf.job.utils.VerifyCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户控制层
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MailService mailService;

    /**
     * 用户注册
     */
    @RequestMapping(value = "user/register.html", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse userRegister(@RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("type") Integer type) {
        // 判断邮箱是否为空
        if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("邮箱或密码不能为空");
        }
        // 校验邮箱是否存在
        boolean result = userService.verifyEmail(email);
        if (!result) {
            return ServerResponse.createByErrorMessage("用户已经存在");
        }
        // 用户名密码MD5加密存入数据库
        int resultCount = userService.addUser(email, password, type);
        // 判断插入影响数据库的条数 大于0 条即成功
        if (resultCount > 0) {
            return ServerResponse.createBySuccessMessage("注册成功");
        }
        return ServerResponse.createByErrorMessage("注册失败");
    }

    /**
     * 用户登录
     */
    @RequestMapping(value = "user/login.html", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse userLogin(@RequestParam("email") String email, @RequestParam("password") String password, HttpServletRequest request) {
        // 判断参数是否为空
        if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("用户名或者密码错误");
        }
        User user = userService.login(email, password);
        if (user != null) {
            // 把用户登录信息写入session
            request.getSession(true).setAttribute(Const.CURRENT_USER, user);
            String logbackUrl = CookieUtil.getValueByCookie(Const.LOGIN_BACK_RUL, request);
            return ServerResponse.createBySuccess("登录成功", logbackUrl);
        }
        return ServerResponse.createByErrorMessage("用户名或者密码错误");
    }

    /**
     * 用户未登录的时候找回密码
     */
    @RequestMapping(value = "user/checkPwd.html", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse checkPwd(@RequestParam("email") String email, HttpServletResponse response) {
        // 判断是否为空
        if (StringUtils.isBlank(email)) {
            return ServerResponse.createByErrorMessage("邮箱输入有误");
        }
        // 去数据库查询条数大于0就是有这个邮箱
        int result = userService.checkPwd(email);
        if (result > 0) {
            // 生成验证码
            String verifyCode = VerifyCodeUtil.createVerifyCode();
            // 将验证码MD5加密之后保存在cookie中
            CookieUtil.addCookie(Const.FIND_PASSWORD, MD5Util.MD5EncodeUtf8(verifyCode), response);
            // 发送验证码到邮箱
            mailService.sendMail(verifyCode, email);

            return ServerResponse.createBySuccessMessage("校验成功");
        }
        return ServerResponse.createByErrorMessage("邮箱账号不存在");
    }

    /**
     * 校验验证码信息
     */
    @RequestMapping("user/verifyCode.html")
    @ResponseBody
    public ServerResponse verifyCode(HttpServletRequest request, @RequestParam("verifyCode") String verifyCode) {
        // 判断是否为空
        if (StringUtils.isBlank(verifyCode)) {
            return ServerResponse.createByErrorMessage("验证码输入有误");
        }
        String cookieValue = CookieUtil.getValueByCookie(Const.FIND_PASSWORD, request);
        // 比较两个加密的验证码是否一样
        if (MD5Util.MD5EncodeUtf8(verifyCode).equals(cookieValue)) {
            return ServerResponse.createBySuccessMessage("验证码校验成功");
        }
        return ServerResponse.createByErrorMessage("验证码输入有误");
    }

    /**
     * 未登录状态下更新密码
     */
    @RequestMapping("user/updatePwd.html")
    @ResponseBody
    public ServerResponse updatePwd(@RequestParam("email") String email, @RequestParam("newPwd") String newPwd) {
        // 判断密码是否为空
        if (StringUtils.isBlank(email) || StringUtils.isBlank(newPwd)) {
            return ServerResponse.createByErrorMessage("密码有误");
        }
        // 去数据库查询影响的条数
        int result = userService.updatePwd(email, newPwd);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("密码有误");
    }

    /**
     * 用户注销功能
     */
    @RequestMapping("user/logout.html")
    public String logout(HttpServletRequest request) {
        // 销毁session
        request.getSession(true).invalidate();
        // 跳转到登录界面
        return "login";
    }

    /**
     * 登录状态下修改密码
     */
    @RequestMapping(value = "user/updatePassword.html", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse updatePassword(HttpServletRequest request, @RequestParam("oldpassword") String oldPwd, @RequestParam("newpassword") String newPwd) {
        // 判断是否为空
        if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)) {
            return ServerResponse.createByErrorMessage("密码有误");
        }
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        int result = userService.findPwd(user.getEmail(), oldPwd);
        // 只能查询出来唯一条数据
        if (result != 1) {
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        // 调用更新密码的方法
        int resultCount = userService.updatePwd(user.getEmail(), newPwd);
        if (resultCount > 0) {
            return ServerResponse.createBySuccessMessage("更新密码成功");
        }
        return ServerResponse.createByErrorMessage("账号或密码存在异常");
    }

}
